#include <iostream>
#include <mysql/mysql.h>
#include <string>

using namespace std;

const string host = "localhost";
const string user = "liusong";
const string password = "Yiren_paranoid";
const string db = "conn";
unsigned int port = 3306;

int main()
{
    // 初始化
    MYSQL *my = mysql_init(nullptr);
    if (my == nullptr)
    {
        cerr << "mysql_init error" << endl;
        return 1;
    }

    // 连接库
    if (mysql_real_connect(my, host.c_str(), user.c_str(), password.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        cerr << "mysql_real_connect error" << endl;
        return 2;
    }
    cout << "mysql_real_connect success" << endl;

    // string sql = "update stu set age=28 where id=1\n";
    // string sql = "insert into stu values(2,20,'李四')\n";
    string sql = "select * from stu\n";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
        cerr << sql << "success" << endl;
    else
        cout << sql << "fail";

    MYSQL_RES *res = mysql_store_result(my);
    // 行数
    int rows = mysql_num_rows(res);
    // 列数
    int fields = mysql_num_fields(res);
    //属性等                  mysql_fetch_fields() 函数会返回一个对象数组，每个对象都包含了一个结果集中字段的信息
    MYSQL_FIELD *fields_arr = mysql_fetch_fields(res);
    for(int i = 0;i<fields;i++)
    {
        //现在只获取每列列名就行
        cout << fields_arr[i].name << "  ";
    }
    cout << "\n";
    for(int i =0;i<rows;i++)
    {
        //获取行结果
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0;j<fields;j++)
        {
            cout << row[j] << "  ";
        }
        cout << "\n";
    }

    mysql_close(my);
    return 0;
}